package com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.web;

import java.util.List;
import java.util.stream.Collectors;

import com.github.pagehelper.PageInfo;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.FlowTenantService;
import com.iwhalecloud.citybrain.flow.platform.manager.common.ErrorCode;
import com.iwhalecloud.citybrain.flow.platform.manager.common.ResponseResult;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.DeleteVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.User;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.app.FlowApp;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.tenant.CheckAuthorizedAppVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.tenant.FlowTenantAddVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.tenant.FlowTenantInfoVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.tenant.FlowTenantQueryVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.tenant.FlowTenantUpdateVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.tenant.FlowUserTenantSubmitVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowAppRepository;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowTenantRepository;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.UserRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Controller - 租户
 *
 * @author lilh
 * @date 2019-01-22 15:01
 */
@RestController
@RequestMapping("/tenant")
@Api(value = "租户管理", tags = "租户管理接口")
public class FlowTenantController {

    @Autowired
    private FlowTenantRepository flowTenantRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private FlowAppRepository flowAppRepository;

    @Autowired
    private FlowTenantService flowTenantService;

    /**
     * 增加
     */
    @ApiOperation(value = "增加")
    @PostMapping("/add")
    public ResponseResult add(@RequestBody @Validated FlowTenantAddVo flowTenantAddVo) {
        User current = userRepository.getCurrentUser();
        /*if (!UserEnum.SUPER.type().equals(current.getUserType())) {
            return ResponseResult.fail(ErrorCode.IDENTITY_MISSING.errCode(), ErrorCode.IDENTITY_MISSING.errMessage());
        }*/
        int insert = flowTenantRepository.insert(flowTenantAddVo);
        if (insert > 0) {
            return ResponseResult.success();
        } else {
            return ResponseResult.fail(ErrorCode.ALREADY_EXIST.errCode(), "名称或编号重复");
        }
    }

    /**
     * 列表
     */
    @ApiOperation(value = "列表")
    @PostMapping("/list")
    public ResponseResult list(@RequestBody FlowTenantQueryVo flowTenantQueryVo) {
        PageInfo<FlowTenantInfoVo> pageInfo = flowTenantRepository.list(flowTenantQueryVo);
        return ResponseResult.success(pageInfo.getList())
                .setTotalCount((int) pageInfo.getTotal())
                .setPageNum(pageInfo.getPageNum())
                .setPageSize(pageInfo.getPageSize());
    }

    /**
     * 详情
     */
    @ApiOperation(value = "详情")
    @GetMapping("/{tenantId}")
    public ResponseResult detail(@PathVariable Integer tenantId) {
        return ResponseResult.success(flowTenantRepository.detail(tenantId));
    }

    /**
     * 更新
     */
    @ApiOperation(value = "更新")
    @PostMapping("/edit")
    public ResponseResult update(@RequestBody @Validated FlowTenantUpdateVo flowTenantUpdateVo) {
        int update = flowTenantRepository.update(flowTenantUpdateVo);
        if (update > 0) {
            return ResponseResult.success();
        } else {
            return ResponseResult.fail(ErrorCode.ALREADY_EXIST.errCode(), "名称或编号重复");
        }
    }

    /**
     * 删除
     */
    @ApiOperation(value = "删除")
    @PostMapping("/delete")
    public ResponseResult delete(@RequestBody DeleteVo deleteVo) {
        List<FlowApp> flowAppInfos = flowAppRepository.listByTenantId(deleteVo.getTenantId());
        if (CollectionUtils.isNotEmpty(flowAppInfos)) {
            return ResponseResult.fail(ErrorCode.TENANT_ASSOCIATED_APP.errCode(), ErrorCode.TENANT_ASSOCIATED_APP.errMessage());
        }
        return ResponseResult.success(flowTenantRepository.delete(deleteVo.getTenantId()));
    }

    /**
     * 列出已授权的租户用户
     *
     * @param tenantId 租户id
     * @return 租户用户列表
     */
    @ApiOperation(value = "列出已授权的租户用户")
    @GetMapping("/listUsers/{tenantId}")
    public ResponseResult listUsers(@PathVariable("tenantId") Integer tenantId) {
        return ResponseResult.success(flowTenantService.listUsersByTenantId(tenantId));
    }

    /**
     * 增加/删除租户用户
     *
     * @param flowUserTenantSubmitVo 用户信息
     * @return 结果
     */
    @ApiOperation(value = "增加/删除租户用户")
    @PostMapping("/submitUsers")
    public ResponseResult submitUsers(@RequestBody FlowUserTenantSubmitVo flowUserTenantSubmitVo) {
        return ResponseResult.success(flowTenantService.addOrDelTenantUsers(flowUserTenantSubmitVo));
    }

    /**
     * 删除前判断是否已授权应用
     *
     * @param checkAuthorizedAppVo 租户用户信息
     * @return 是否已授权应用等信息
     */
    @ApiOperation(value = "删除前判断是否已授权应用")
    @PostMapping("/getAuthorizedApp")
    public ResponseResult getAuthorizedApp(@RequestBody CheckAuthorizedAppVo checkAuthorizedAppVo) {
        List<FlowApp> flowApps = flowTenantService.listAppByTenantAndUserCode(checkAuthorizedAppVo.getTenantId(), checkAuthorizedAppVo.getUserCode());
        return ResponseResult.success(flowApps.stream().map(FlowApp::getAppName).collect(Collectors.joining(",")));
    }

}
